<template>
	<view class="">
		<view class="" @touchmove.stop.prevent="a = false" @catchtouchmove="a = false" v-show="!loadFlag">
			<view class="" style="">
				<swiper style="height: 100vh;width: 100vw;" :circular="true" @change="swiperChange"
					:current="activeCurrent">
					<swiper-item v-for="(item,index) in imgsList" :key="index">
						<video :src="item.src" v-if="img_type == 5" @click="cssClick"
							style="height: 100vh;width: 100vw;display: flex;"></video>
						<image :src="item.src" v-else @click="cssClick"
							style="height: 100vh;width: 100vw;display: flex;" mode="aspectFill">
						</image>
					</swiper-item>
				</swiper>
			</view>
			<view class="date-container">
				<text class="time">{{time}}</text>
				<text class="date">{{date}}</text>
			</view>
			<view class="bottom" :class="cssTran ? 'closeCss' : 'openCss'" v-if="!loadFlag">
				<view class="num">{{indexCurrent}} / {{imgsList.length}}</view>
				<view class="nav-box">
					<view class="nav-tab" @click="backClick">
						<image src="/static/icon/back.png" style="width: 44rpx;" mode="widthFix"></image>
						<!-- <u-icon name="/static/icon/back.png" :size="44"></u-icon> -->
						<text>返回</text>
					</view>
					<!-- 	<view class="nav-tab" @click="collectClick()">
						<u-icon :name="isColl?'/static/icon/coll_art.png':'/static/icon/coll.png'" :size="40"></u-icon>
						<text>{{isColl?'已收藏':'收藏'}}</text>
					</view> -->
					<view class="nav-tab" @click="winClick">
						<image src="/static/icon/duihuan.png" style="width: 42rpx;" mode="widthFix"></image>
						<!-- <u-icon name="/static/icon/duihuan.png" :size="42"></u-icon> -->
						<text>下载</text>
					</view>
					<!-- <view class="nav-tab" @click="zanClick(isZan)">
						<u-icon :name="isZan?'/static/icon/zan_art.png':'/static/icon/zan.png'" :size="isZan?48:42">
						</u-icon>
						<text>{{isZan?'已点赞':'点赞'}}</text>
					</view> -->
					<view class="nav-tab">
						<image src="/static/icon/shares.png" style="width: 44rpx;" mode="widthFix"></image>
						<!-- <u-icon name="/static/icon/shares.png" :size="44"></u-icon> -->
						<text>分享</text>
						<button open-type="share"
							style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;opacity: 0;"></button>
					</view>
				</view>
			</view>
			<!-- <view v-if="tipsShow" style="position: absolute;top: 0;left: 0;width: 100vw;height: 100vh;z-index: 11;" @click="tipsClick">
				<image src="../../static/tips.png" style="width: 100%;height: 100%;display: flex;" mode="aspectFill"></image>
			</view> -->


		</view>
		<view class="loading_page" v-show="loadFlag">
			<image src="/static/loading/loading.gif"></image>
		</view>
	</view>
</template>

<script>
	var rewardedVideoAd = null
	import {
		advertisingData11
	} from "@/mixin/advertisingData1.js"
	import {
		mixinAdvertising
	} from "@/mixin/advertising.js"
	export default {
		mixins: [advertisingData11, mixinAdvertising],
		data() {
			return {
				loadFlag:false,
				imgsList: [],
				// 创作者数据
				framerData: {},
				// 创作者code
				home_code: "",
				// 图片类型
				img_type: "",
				time: "",
				date: "",
				activeCurrent: 0,
				indexCurrent: 1,
				upImg: "",
				page: 1

			}
		},
		// framer_id=001&img_type=2&up_img=https%253A%252F%252Fvkceyugu.cdn.bspapp.com%252FVKCEYUGU-efee5dd1-84a8-4e86-a111-9bb95647d70d%252F2b585f87-7c80-4a90-ace5-2becfa33a9e7.png&__id__=1
		onShareAppMessage() {
			return {
				title: "精选壁纸头像免费拿，入驻丰厚奖励",
				path: "/pages/index/index"
			};
		},
		onLoad(e) {
			// framer_id=001&img_type=2&__id__=2
			this.home_code = e.framer_id
			this.img_type = e.img_type
			this.upImg = e.up_img
			this.init1()
			this.getFramer()
			this.getImgsList()
			setTimeout(() => {
				// this.initAd()
			}, 1000)
			uni.getSavedFileList({
				// 获取文件列表
				success(res) {
					res.fileList.forEach((val, key) => {
						// 遍历文件列表里的数据        
						// 删除存储的垃圾数据   
						uni.removeSavedFile({
							filePath: val.filePath,
						});
					})
				}
			})
		},
		methods: {
			initAd() {
				var advertising = uni.getStorageSync('advertising')
				var adUnitId = this.advertisingData1(this.advertisingDataType.popUpList)
				// this.adUnitIdbanner = this.advertisingData1(this.advertisingDataType.bannerList)
				if (advertising.advertisingOpen == 1) {
					// 在页面中定义插屏广告
					let interstitialAd = null

					// 在页面onLoad回调事件中创建插屏广告实例
					if (uni.createInterstitialAd) {
						interstitialAd = uni.createInterstitialAd({
							adUnitId: adUnitId
						})
						interstitialAd.onLoad(() => {})
						interstitialAd.onError((err) => {})
						interstitialAd.onClose(() => {})
					}

					// 在适合的场景显示插屏广告
					if (interstitialAd) {
						interstitialAd.show().catch((err) => {
							console.error(err)
						})
					}
				}


			},

			// 获取创作者
			async getFramer() {
				var userInfo = uni.getStorageSync('userInfo') || {}
				var data = await this.$api.getData({
					dbName: "wx_framer",
					whereJson: {
						home_code: this.home_code || '',
					}
				},true)
				if (data.rows[0]) {
					this.framerData = data.rows[0]
				}

			},
			// 获取图片
			async getImgsList() {
				let filter = {
					img_type: Number(this.img_type),
					framer_id: this.home_code,
				}
				if (!this.img_type) {
					delete filter.img_type
				}
				var data = await this.$api.getData({
					dbName: "wx_imgs",
					sortRule:[
						{
							"name": "add_data",
							"type": "asc"
						}
					],
					whereJson: {
						"src": this.upImg
					},
					pageIndex: 1,
					pageSize: 10
				},true)

				this.imgsList = data.rows
				var currentIndex = this.imgsList.findIndex(item => {
					return item.src == this.upImg
				})
				this.activeCurrent = currentIndex
				this.indexCurrent = (Number(currentIndex)) + 1
			},
			async getDate() {
				var t = new Date(),
					e = (t.getFullYear(), t.getMonth() + 1),
					o = t.getDate(),
					a = t.getHours(),
					n = t.getMinutes(),
					i = (t.getSeconds(), e + "月" + o + "日"),
					s = [a, n].map(this.formatNumber).join(":");
				console.log(i), console.log(s), this.setData({
					date: i,
					time: s
				});
			},
			formatNumber: function(t) {
				return (t = t.toString())[1] ? t : "0" + t;
			},
			// 下载
			async winClick() {
				var that = this
				const startTime = new Date(new Date().toLocaleDateString()).getTime()
				const endTime = new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1

				var user = uni.getStorageSync('user')
				// var signData = await uniCloud.callFunction({
				// 	name: 'sign_flag',
				// 	data: {
				// 		openid: user.openid,
				// 		"startTime": startTime,
				// 		"endTime": endTime
				// 	}
				// })

				// if (signData.result.success) {
				// 	uni.showToast({
				// 		title: "今天下载次数已用完，请明天再下载",
				// 		icon: "none"
				// 	})
				
				// 	return
				// }

				// 获取图片信息
				var url = that.imgsList[that.indexCurrent - 1].src
				var extension = url.substring(url.lastIndexOf('.') + 1)
				let fileName = new Date().valueOf();
				if (this.img_type == 5) {
					if (extension.includes('&')) {
						extension = 'pm4'
					}
				} else {
					if (extension.includes('&')) {
						extension = 'png'
					}
				}
				var advertising = uni.getStorageSync('advertising')
				console.log(advertising,'asdfasdfasd')
				if (advertising.advertisingOpen != 1) {
					that.little(url, extension, fileName)
					return
				}
				uni.showModal({
					title: '提示',
					content: '需要看广告视频才能获得',
					success(res) {
						if (res.confirm) {

							// uni.showLoading({
							// 	title: "下载中..."
							// })


							that.kanguangao3(() => {
								that.little(url, extension, fileName)
							})

						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});


			},
			dateFormat(fmt, date) {
				let ret
				const opt = {
					"Y+": date.getFullYear().toString(), // 年
					"m+": (date.getMonth() + 1).toString(), // 月
					"d+": date.getDate().toString(), // 日
					"H+": date.getHours().toString(), // 时
					"M+": date.getMinutes().toString(), // 分
					"S+": date.getSeconds().toString(), // 秒
				}
				for (let k in opt) {
					ret = new RegExp("(" + k + ")").exec(fmt)
					if (ret) {
						fmt = fmt.replace(
							ret[1],
							ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
						)
					}
				}
				return fmt
			},
			// 添加下载数量
			async addDownloadNum() {
				var userInfo = uni.getStorageSync('user')
				let imgItem = this.imgsList[this.activeCurrent]
				uni.request({
					url: 'https://pv.sohu.com/cityjson?ie=utf-8', //仅为示例，并非真实接口地址。
					method: "POST",
					success: async (res) => {
						var data = /\{(.+?)\}/gi.exec(res.data)
						if (data[0]) {
							var dataIP = JSON.parse(data[0])
							console.log(dataIP,'asdfasdfasd')
							var user = uni.getStorageSync('user')
							uniCloud.callFunction({
									name: 'add-award',
									data: {
										dataIP: dataIP,
										filter: {
											framer_id: imgItem.framer_id,
											img_id: imgItem._id,
											add_data: this.dateFormat("YYYY-mm-dd", new Date()),
											user_id: imgItem.user_id,
										},
										addData: {
											img_type: imgItem.img_type,
											src: imgItem.src,
											framer_id: imgItem.framer_id,
											img_id: imgItem._id,
											status: 1,
											user_id: imgItem.user_id,
											user_name: imgItem.user_name || '暂无',
											download_user: [user || ''],
											framer_name: imgItem.framer_name,
											up_date: [this.dateFormat("YYYY-mm-dd HH:MM:SS",
												new Date())],
											add_data: this.dateFormat("YYYY-mm-dd", new Date())
										},
										upData: {
											download_user: user || {},
											up_date: this.dateFormat("YYYY-mm-dd HH:MM:SS", new Date())
										}
									}
								})
								.then(res => {
									uni.showToast({
										title: "下载成功"
									})
								});




						}
					}
				});


			},
			// 下载
			little(url, extension, fileName) {
				// #ifdef MP-WEIXIN
				var USER_DATA_PATH = wx.env.USER_DATA_PATH
				// #endif
				// #ifdef MP-TOUTIAO
				var USER_DATA_PATH = tt.getEnvInfoSync().common.USER_DATA_PATH
				// #endif
				uni.showLoading({
					title: "下载中..."
				})
				var that = this
				uni.downloadFile({
					url: url,
					filePath: USER_DATA_PATH + '/' + fileName + '.' + extension,
					success: (res) => {
						var benUrl = res.filePath
						//图片保存到本地相册
						if (that.img_type == 5) {
							var apiType = 'saveVideoToPhotosAlbum'
						} else {
							var apiType = 'saveImageToPhotosAlbum'
						}
						uni[apiType]({
							filePath: benUrl,
							//授权成功，保存图片
							success: function(data) {
								// uni.hideLoading()
								var advertising = uni.getStorageSync('advertising')
								console.log(advertising)
								if (advertising.advertisingOpen == 1) {
									// 添加下载数据量
									that.addDownloadNum()
								} else {
									uni.showToast({
										title: "下载成功"
									})
								}
								var advertising = uni.getStorageSync('advertising')
								
								if(advertising.advertisingOpen == 1){
									setTimeout(() => {
										uni.showModal({
											title: '提示',
											content: '邀请您加入创作者',
											success(res) {
												if (res.confirm) {
													uni.navigateTo({
														url: "/pages/common/extension"
													})
												}
											}
										})
									},2000)
								}
								

							},
							//授权失败
							fail: function(err) {
								console.log(err, '111111122222')
								if (err.errMsg) {
									//重新授权弹框确认
									uni.showModal({
										title: '温馨提示',
										content: '授权失败，请稍后重新获取',
										showCancel: false
									});
								}
								uni.hideLoading()
							}
						});
					},
					fail: (error) => {
						console.log(error)
					}
				})
			},


			// 返回
			backClick() {
				uni.navigateBack()
			},
			// 收藏
			async collectClick() {
				var that = this
				if (!that.vuex_user) {
					that.loginShow = true
					return
				}

				if (that.collStatus) {
					uni.showToast({
						icon: 'none',
						title: '太快啦，歇一会再试试',
						mask: true,
						duration: 1000
					})
					return
				}
				that.collStatus = true
				// 先显示  再请求 视觉上更适应
				that.isColl = !that.isColl

				let coll = await uniCloud.callFunction({
					name: 'zan_and_coll',
					data: {
						dbName: that.vuex_isShenHe ? "wx_cover_shenhe" : "wx_cover",
						type: 'coll',
						userId: that.vuex_user._id,
						filter: {
							"_id": that.detail._id,
							"coll.user_id": that.vuex_user._id
						}
					},
				})
				if (!coll.result.success) {
					// 更新失败
					uni.showToast({
						mask: true,
						icon: 'none',
						title: coll.result.msg,
						duration: 2000
					})
					that.isColl = !that.isColl
				}
				setTimeout(function() {
					that.collStatus = false
				}, 5000)
			},
			// 点赞
			async zanClick(zan) {
				var that = this
				if (!that.vuex_user) {
					that.loginShow = true
					return
				}

				var timestamp = new Date().getTime()
				if (zan) {
					uni.showToast({
						icon: 'none',
						title: '你已经点过赞啦~',
						mask: true,
						duration: 1000
					})
				} else {
					if (that.zanStatus) {
						uni.showToast({
							icon: 'none',
							title: '太快啦，歇一会再试试',
							mask: true,
							duration: 1000
						})
						return
					}
					that.zanStatus = true
					// 先显示  再请求 视觉上更适应
					that.isZan = !that.isZan

					let zan = await uniCloud.callFunction({
						name: 'zan_and_coll',
						data: {
							dbName: that.vuex_isShenHe ? "wx_cover_shenhe" : "wx_cover",
							type: 'zan',
							userId: that.vuex_user._id,
							filter: {
								"_id": that.detail._id,
								"zan.user_id": that.vuex_user._id
							}
						},
					})
					if (!zan.result.success) {
						// 更新失败
						uni.showToast({
							mask: true,
							icon: 'none',
							title: zan.result.msg,
							duration: 2000
						})
						that.isZan = !that.isZan
					}
				}
				setTimeout(function() {
					that.zanStatus = false
				}, 5000)
			},
			cssClick() {
				this.cssTran = !this.cssTran
			},




			swiperChange(e) {
				this.indexCurrent = e.detail.current + 1
			},
		}

	}
</script>
<style lang="scss">
	.bottom {
		position: fixed;
		left: 4%;
		right: 0;
		width: 92%;
		height: 52px;
		box-shadow: 0 0px 8px rgba(0, 0, 0, 0.06);
		background: rgba(0, 0, 0, 0.94);
		border-radius: 49px;
		z-index: 10;
		opacity: 0.8;

		.num {
			position: absolute;
			top: -20rpx;
			top: -70rpx;
			left: 44%;
			background: rgba(0, 0, 0, 0.6);
			color: #FFF;
			padding: 4rpx 20rpx;
			font-size: 12px;
			border-radius: 36px;
		}
	}

	.nav-tab {
		position: relative;
		width: 100%;
		height: 52px;
		font-size: 12px;
		color: #D8D8D8;
		font-weight: 400;

		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.nav-box {
		/* position: absolute; */
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		width: 100%;
		box-sizing: border-box;
	}

	.openCss {
		animation-name: openLinear;
		animation-duration: 0.8s;
		animation-iteration-count: 1;
		bottom: 3%;
	}

	@keyframes openLinear {
		0% {
			transform: translateY(92px);
		}

		100% {
			transform: translateY(0px);
		}
	}

	.closeCss {
		animation-name: closeLinear;
		animation-duration: 0.8s;
		animation-iteration-count: 1;
		bottom: -52px;
	}

	@keyframes closeLinear {
		0% {
			transform: translateY(-92px);
		}

		100% {
			transform: translateY(0px);
		}
	}

	.u-indicator-item-number {
		padding: 6rpx 16rpx;
		line-height: 1;
		background-color: rgba(0, 0, 0, 0.3);
		border-radius: 100rpx;
		font-size: 26rpx;
		color: rgba(255, 255, 255, 0.8);
	}

	.date-container {
		width: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		position: absolute;
		top: 150rpx;
		opacity: .9;
	}

	.time {
		font-size: 120rpx;
		color: #fff;
	}

	.date {
		font-size: 40rpx;
		color: #fff;
	}
</style>
